import uuid

import pandas as pd
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import json
import numpy as np
from base_configs.models import EmbeddingType
from history_qa.models import HistoryQA, ProjectInfo, PartitionInfo, vector_db, embedding_name2dim_dict, choose_model
from datetime import datetime
import time
from tqdm import tqdm
from logging import getLogger
logger = getLogger("log")

# 检查embedding是否新增了维度
dim_list = list(set(embedding_name2dim_dict.values()))


@csrf_exempt
def insert_qa_data(request):
    ## 加载参数
    history_qa = request.POST.get('history_qa', None)  # 历史问答对
    if not history_qa:
        return JsonResponse({"status": 401, "message": "请输入参数history_qa!"})
    history_qa = json.loads(history_qa)
    
    project_name = request.POST.get("project_name", None)  # 项目名称
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"project_name不能为空！"})
        
    partition_name = request.POST.get("partition_name", None)
    if partition_name is None:
        return JsonResponse({"status": 401, "message": f"partition_name不能为空！"})
    
    user = request.POST.get("user", "")  # 用户名，允许空
    session_id = request.POST.get("session_id", "")  # 问答轮次id，允许空
    feedback = request.POST.get("feedback", "0")
    user_id = request.POST.get("user_id", None)
    user_id = user_id if user_id else None
    source = request.POST.get("source", "")
    embedding_type = request.POST.get("embedding_type", "m3e-base")  # embedding类型
    meta_data = request.POST.get("meta_data", None)
    if meta_data:
        meta_data = json.loads(meta_data)
    comment = request.POST.get("comment", None)  # embedding类型
    if embedding_type not in embedding_name2dim_dict:
        return JsonResponse({
            "status": 402, 
            "message": "embedding_type必须为'{}'其中之一!".format(",".join(list(embedding_name2dim_dict.keys())))})
    embedding_dim = embedding_name2dim_dict[embedding_type]

    project_qs = ProjectInfo.objects.filter(name=project_name)
    if project_qs.exists():
        project = project_qs[0]
        dim_list = project.dims.split(",")
        if project.status == 0:
            project.status = 1
            project.save()
        if str(embedding_dim) not in dim_list:
            dim_list.append(str(embedding_dim))
            project.dims = ",".join(dim_list)
            project.save()
            real_project_name = project.real_name
            return_status = vector_db.build_collection(project_name, real_project_name, embedding_dim)

    else:
        real_project_name = "historyqa_" + project_name + "_" + str(uuid.uuid1()).replace('-', '')
        project = ProjectInfo(name=project_name, real_name=real_project_name, dims=str(embedding_dim))
        project.save()
        return_status = vector_db.build_collection(project_name, real_project_name, embedding_dim)
    
    model = choose_model(embedding_type)
    
    query, answer = history_qa[-1]
    if len(query.encode('utf-8')) >= 2048:
        return JsonResponse({"status": 401, "message": "问题长度超过限制!"})

    partition, _ = PartitionInfo.objects.get_or_create(name=partition_name, project_name=project)
    if partition.status == 0:
        partition.status = 1
        partition.save()

    records = HistoryQA.objects.filter(question=query, answer=answer, project_name=project, partition_name=partition, user=user, session_id=session_id, embedding_type__name=embedding_type, status=1)
    if not records.exists():
        code = str(uuid.uuid4().hex[:8]) + str(int(round(time.time() * 1000)))
        query_embedding = model(query)
        # 写入到milvus中
        tmp_result_list = [
            [code],
            [query],
            [query_embedding],
            [user],
            [session_id],
            [embedding_type],
            [source],
            [datetime.now().strftime("%Y-%m-%d %H:%M:%S")]
        ]
        return_status, error_info = vector_db.insert_data(data=tmp_result_list, collection_name=project_name, partition_name=partition_name, embedding_dim=embedding_dim)
        if not return_status:
            return JsonResponse({"status": 403, "msg": f"写入失败，发生错误{error_info}！"})
        embedding_type_obj = EmbeddingType.objects.get(name=embedding_type)
        qa_data = HistoryQA(
            code=code,
            question=query,
            answer=answer,
            source=source,
            project_name=project,
            partition_name=partition,
            user=user,
            feedback=str(feedback),
            user_id=user_id,
            session_id=session_id,
            embedding_type=embedding_type_obj,
            meta_data=str(meta_data),
            comment=comment
        )
        qa_data.save1()
        return JsonResponse({"status": 200, "msg": "请求成功，成功插入1条对话记录！"})
    return JsonResponse({"status": 200, "msg": "请求成功，对话记录已存在，未插入！"})        
    
    
@csrf_exempt
def insert_qa_data_batch(request):
    ## 加载参数
    history_qa_list = request.POST.get('history_qa', None)  # 历史问答对
    if not history_qa_list:
        return JsonResponse({"status": 401, "message": "请输入参数history_qa!"})
    history_qa_list = json.loads(history_qa_list)
    project_name = request.POST.get("project_name", None)  # 项目名称
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"project_name不能为空！"})

    project = ProjectInfo.objects.get_or_create(name=project_name)
    if project.status == 0:
        project.status = 1
        project.save()
        real_project_name = "historyqa_" + project_name + "_" + str(uuid.uuid1()).replace('-', '')
        return_status = vector_db.build_collection(project_name, real_project_name)
        
    partition_name = request.POST.get("partition_name", None)
    if partition_name is None:
        return JsonResponse({"status": 401, "message": f"partition_name不能为空！"})
    
    user = request.POST.get("user", "")  # 用户名，允许空
    session_id = request.POST.get("session_id", "")  # 问答轮次id，允许空
    embedding_type = request.POST.get("embedding_type", "m3e-base")
    if embedding_type not in embedding_name2dim_dict:
        return JsonResponse({
            "status": 402, 
            "message": "embedding_type必须为'{}'其中之一!".format(",".join(list(embedding_name2dim_dict.keys())))})
    embedding_dim = embedding_name2dim_dict[embedding_type]
    
    model = choose_model(embedding_type)
    embedding_type_obj = EmbeddingType.objects.get(name=embedding_type)
    save_num = 2000
    total_num = len(history_qa_list)
    insert_num = 0

    partition = PartitionInfo.objects.get_or_create(name=partition_name, project_name=project)
    if partition.status == 0:
        partition.status = 1
        partition.save()
    
    mysql_insert_list = []
    milvus_insert_dict = {
        "code": [], 
        "question": [], 
        "feature": [], 
        "user": [],
        "session_id": [],
        "embedding_type": [],
        "source": [],
        "create_time": []
    }
    for history_qa in tqdm(history_qa_list):
        query, answer, source, feedback, user_id = history_qa[-1]
        if len(query.encode('utf-8')) < 2048:
            # 每save_num条存入一次，最后存入一次
            # 写入到mysql中
            records = HistoryQA.objects.filter(question=query, project_name=project, partition_name=partition, user=user, session_id=session_id, embedding_type__name=embedding_type, status=1)
            if not records.exists():
                code = str(uuid.uuid4().hex[:8]) + str(int(round(time.time() * 1000)))
                qa_data = HistoryQA(
                    code=code,
                    question=query,
                    answer=answer,
                    source=source,
                    project_name=project,
                    partition_name=partition,
                    user=user,
                    feedback=str(feedback),
                    user_id=user_id,
                    session_id=session_id,
                    embedding_type=embedding_type_obj
                )
                mysql_insert_list.append(qa_data)
                # 写入到milvus中
                milvus_insert_dict["code"].append(code)
                milvus_insert_dict["question"].append(query)
                milvus_insert_dict["user"].append(user)
                milvus_insert_dict["session_id"].append(session_id)
                milvus_insert_dict["embedding_type"].append(embedding_type)
                milvus_insert_dict["source"].append(source)
                milvus_insert_dict["create_time"].append(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        
        # 写入
        if len(milvus_insert_dict["code"]) == save_num:
            # 把query embedding化，并进行归一化处理
            query_embedding = []
            for q in milvus_insert_dict["question"]:
                query_embedding.append(model(q))
            query_embedding = np.array(query_embedding).astype("float32")
            # query_embedding = model(milvus_insert_dict["question"])
            # query_embedding = query_embedding / np.linalg.norm(query_embedding, axis=1, keepdims=True)
            milvus_insert_dict["feature"] = query_embedding
            HistoryQA.objects.bulk_create(mysql_insert_list)
            milvus_insert_data = [
                milvus_insert_dict["code"], 
                milvus_insert_dict["question"],
                milvus_insert_dict["feature"],
                milvus_insert_dict["user"],
                milvus_insert_dict["session_id"],
                milvus_insert_dict["embedding_type"],
                milvus_insert_dict["source"],
                milvus_insert_dict["create_time"],
            ]
            vector_db.insert_data(data=milvus_insert_data, collection_name=project_name, partition_name=partition_name, embedding_dim=embedding_dim)
            
            mysql_insert_list = []
            milvus_insert_dict = {
                "code": [], 
                "question": [], 
                "feature": [], 
                "user": [],
                "session_id": [],
                "embedding_type": [],
                "source": [],
                "create_time": []
            }
            insert_num += save_num
    # 不足save_num条
    if len(milvus_insert_dict["code"]) > 0:
        query_embedding = []
        for q in milvus_insert_dict["question"]:
            query_embedding.append(model(q))
        query_embedding = np.array(query_embedding).astype("float32")
        # query_embedding = model(milvus_insert_dict["question"])
        # query_embedding = query_embedding / np.linalg.norm(query_embedding, axis=1, keepdims=True)
        milvus_insert_dict["feature"] = query_embedding
            
        HistoryQA.objects.bulk_create(mysql_insert_list)
        milvus_insert_data = [
                milvus_insert_dict["code"], 
                milvus_insert_dict["question"],
                milvus_insert_dict["feature"],
                milvus_insert_dict["user"],
                milvus_insert_dict["session_id"],
                milvus_insert_dict["embedding_type"],
                milvus_insert_dict["source"],
                milvus_insert_dict["create_time"],
            ]
        vector_db.insert_data(data=milvus_insert_data, collection_name=project_name, partition_name=partition_name, embedding_dim=embedding_dim)
        insert_num += len(milvus_insert_dict["code"])
        
    return JsonResponse({"status": 200, "msg": f"请求成功，总共{total_num}条，成功写入{insert_num}条，{total_num-insert_num}条重复！"})


def get_milvus_results(query_embedding, session_id, embedding_type, embedding_dim, collection_name, partition_name, similar_type, topk):
    res = vector_db.get_hybrid_vector_search(query_embedding, session_id, embedding_type, embedding_dim, collection_name, partition_name, similar_type, topk=topk, nprobe=10, is_dict=True)
    return res


def del_repeat(data, key):
    new_data = []
    values = set()
    for d in data:
        if d[key] not in values:
            new_data.append(d)
            values.add(d[key])
    return new_data


@csrf_exempt
def query_question(request):
    start_time = time.time()
    ## 加载参数
    query = request.POST.get('query', None)  # 历史问答对
    if not query:
        return JsonResponse({"status": 401, "message": "请输入参数query!"})
    
    user = request.POST.get("user", "")  # 用户名，允许空
    session_id = request.POST.get("session_id", None)  # 问答轮次id，允许空
    embedding_type = request.POST.get("embedding_type", None)  # embedding类型，默认是None
    
    
    project_name = request.POST.get("project_name", None)  # 项目名称
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"project_name不能为空！"})
    # project_name = "historyqa_" + project_name
    try:
        project = ProjectInfo.objects.get(name=project_name, status=1)
    except ProjectInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"项目 {project_name}不存在!"})
        
    partition_name = request.POST.get("partition_name", None)
    if partition_name is None:
        return JsonResponse({"status": 401, "message": f"partition_name不能为空！"})
    try:
        partition = PartitionInfo.objects.get(name=partition_name, project_name=project, status=1)
    except PartitionInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"项目 {project_name}下的历史对话库 {partition_name}不存在!"})
    
    
    similar_type = request.POST.get("similar_type", "IP")
    topk = request.POST.get("topk", 3)  # 选取回答topk，默认是3
    if not isinstance(topk, int):
        topk = int(topk)

    if embedding_type is None:
        ## 查看当前项目库中所有的embedding类型
        embedding_type_list = HistoryQA.objects.filter(project_name=project, partition_name=partition).values("embedding_type__name").distinct()
        embedding_type_list = [e["embedding_type__name"] for e in list(embedding_type_list)]
        embedding_dim_list = [embedding_name2dim_dict[et] for et in embedding_type_list]
    else:
        if embedding_type not in embedding_name2dim_dict:
            return JsonResponse({
                "status": 402, 
                "message": "embedding_type必须为'{}'其中之一!".format(",".join(list(embedding_name2dim_dict.keys())))})
        embedding_type_list = [embedding_type]
        embedding_dim_list = [embedding_name2dim_dict[embedding_type]]
        
        
    history_dialogue_results = []
    qa_records_results = []
    # 全局检索
    for embedding_type, embedding_dim in zip(embedding_type_list, embedding_dim_list):
        model = choose_model(embedding_type)
        print(time.time()-start_time)
        query_embedding = model(query)
        print(time.time()-start_time)
        # 在milvus中查结果，返回code
        # session检索
        time1 = time.time()
        if session_id is not None:
            history_dialogue_res_list = get_milvus_results([query_embedding], session_id, embedding_type, embedding_dim, project_name, partition_name, similar_type, topk)
            if history_dialogue_res_list is None:
                return JsonResponse({'status': 200, 'message': "当前历史对话库下不存在embedding类型为{}的数据！".format(embedding_type), 'results': {'history_dialogue': {'data': [], 'time': time.time()-time1}, 'qa_records': {'data': [], 'time': 0}}})
            history_dialogue_results.extend(history_dialogue_res_list)
        time2 = time.time()
        # 全局检索
        qa_records_list = get_milvus_results([query_embedding], None, embedding_type, embedding_dim, project_name, partition_name, similar_type, topk)
        if qa_records_list is None:
            return JsonResponse({'status': 200, 'message': "当前历史对话库下不存在embedding类型为{}的数据！".format(embedding_type), 'results': {'history_dialogue': {'data': [], 'time': time2-time1}, 'qa_records': {'data': [], 'time': time.time()-time2}}})
        qa_records_results.extend(qa_records_list)
        time3 = time.time()
    
    history_dialogue_results = del_repeat(history_dialogue_results, "code")
    qa_records_results = del_repeat(qa_records_results, "code")
    if similar_type == "IP":
        reverse = True
    else:
        reverse = False
    # 去重后topk
    history_dialogue_results = sorted(history_dialogue_results, key=lambda x: x["score"], reverse=reverse)[:topk]
    qa_records_results = sorted(qa_records_results, key=lambda x: x["score"], reverse=reverse)[:topk]
    ## 根据code去mysql数据库中反查answer
    s = time.time()
    history_dialogue_results = [
        {
            "question": r["question"], 
            "answer": HistoryQA.objects.get(code=r["code"]).answer,
            "source": r["source"],
            "score": r["score"]
        } 
        for r in history_dialogue_results
    ]
    valid_history_dialogue_results = []
    for r in history_dialogue_results:
        if r not in valid_history_dialogue_results:
            valid_history_dialogue_results.append(r)
    qa_records_results = [
        {
            "question": r["question"], 
            "answer": HistoryQA.objects.get(code=r["code"]).answer,
            "source": r["source"],
            "score": r["score"]
        } 
        for r in qa_records_results
    ]
    valid_qa_records_results = []
    for r in qa_records_results:
        if r not in valid_qa_records_results:
            valid_qa_records_results.append(r)
    e = time.time()
    return JsonResponse({"status": 200, "results": {"history_dialogue": {"data": valid_history_dialogue_results, "time": time2-time1}, "qa_records": {"data": valid_qa_records_results, "time": time3 - time2}}})
    
    
@csrf_exempt
def build_project(request):
    project_name = request.POST.get('project_name', None)
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"project_name不能为空！"})

    real_project_name = "historyqa_" + project_name + "_" + str(uuid.uuid1()).replace('-', '')
    try:
        record = ProjectInfo.objects.get(name=project_name)
        if record.status == 1:
            return JsonResponse({"status": 402, "message": f"项目 {project_name}已存在！"})
        else:
            record.status = 1
            record.real_name = real_project_name
            record.save()
    except ProjectInfo.DoesNotExist:
        project_info = ProjectInfo(
            name=project_name,
            real_name=real_project_name,
        )
        project_info.save()
    return JsonResponse({"status": 200, "message": f"项目 {project_name}创建成功！"})
    # return_status = vector_db.build_collection(project_name, real_project_name)
    # if return_status:
    #     return JsonResponse({"status": 200, "message": f"项目 {project_name}创建成功！"})
    # else:
    #     return JsonResponse({"status": 200, "message": f"项目 {project_name}创建失败！"})

    
@csrf_exempt
def delete_project(request):
    project_name = request.POST.get('project_name', None)
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"project_name不能为空！"})
    # project_name = "historyqa_" + project_name
    try:
        project = ProjectInfo.objects.get(name=project_name, status=1)
        real_project_name = project.real_name
    except ProjectInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"项目 {project_name}不存在!"})
    partition_list = PartitionInfo.objects.filter(project_name=project).delete()
         
    
    return_status = vector_db.del_collection(project_name, real_project_name)
    if return_status:
        record_list = HistoryQA.objects.filter(project_name=project).delete()
        project.status = 0
        project.save()
        return JsonResponse({"status": 200, "message": f"项目 {project_name}删除成功！"})
    else:
        return JsonResponse({"status": 200, "message": f"项目 {project_name}删除失败！"})
    
    
@csrf_exempt  
def delete_partition(request):
    project_name = request.POST.get('project_name', None)
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"参数project_name不能为空!"})
    partition_name = request.POST.get('partition_name', None)
    if partition_name is None:
        return JsonResponse({"status": 401, "message": f"参数partition_name不能为空!"})
    try:
        project = ProjectInfo.objects.get(name=project_name, status=1)
    except ProjectInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"项目 {project_name}不存在!"})
    try:
        partition = PartitionInfo.objects.get(name=partition_name, project_name=project, status=1)
    except PartitionInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"历史对话库 {partition_name}不存在!"})
    
    return_status = vector_db.del_partition(project_name, partition_name)
    if return_status:
        partition_records_list = HistoryQA.objects.filter(project_name=project, partition_name=partition).delete()
        partition.delete()
    
        return JsonResponse({"status": 200, "message": f"项目{project_name}下的历史对话库{partition_name}删除成功！"})
    return JsonResponse({"status": 200, "message": f"项目{project_name}下的历史对话库{partition_name}删除失败！"})



@csrf_exempt  
def rename_project(request):
    project_name = request.POST.get('project_name', None)
    new_project_name = request.POST.get('new_project_name', None)
    
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"参数project_name不能为空!"})
    if new_project_name is None:
        return JsonResponse({"status": 401, "message": f"参数new_project_name不能为空!"})
    # project_name = "historyqa_" + project_name
    try:
        project = ProjectInfo.objects.get(name=project_name, status=1)
        # real_project_name = project.real_name
        # new_project_name = "historyqa_" + new_project_name
        # real_new_project_name = new_project_name + "_" + str(uuid.uuid1()).replace('-', '')
    except ProjectInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"项目 {project_name[10:]}不存在!"})

    # milvus数据库改名
    return_status = vector_db.rename_collection(project_name, new_project_name)
    if return_status:
        # mysql数据库collection改名
        project.name = new_project_name
        project.save()
        return JsonResponse({"status": 200, "message": f"项目名称更改成功！"})
    else:
        return JsonResponse({"status": 200, "message": f"项目名称更改失败！"})


@csrf_exempt
def recover_data_from_mysql(request):
    project_name = request.POST.get("project_name", None)
    if project_name:
        records = list(HistoryQA.objects.filter(project_name__name=project_name).values("code", "question", "answer",
                                                      "user_id", "feedback", "session_id", "source", "create_time",
                                                      "project_name__name", "partition_name__name",
                                                      "embedding_type__name",
                                                      "meta_data"
                                                      ))
    else:
        records = list(HistoryQA.objects.all().values("code", "question", "answer",
                                                     "user_id", "feedback", "session_id", "source", "create_time",
                                                     "project_name__name", "partition_name__name", "embedding_type__name",
                                                     "meta_data"
                                                     ))
    records_df = pd.DataFrame(records)
    records_df = records_df.rename(columns={
        "project_name__name": "project_name",
        "partition_name__name": "partition_name",
        "embedding_type__name": "embedding_type"
    })
    for (tmp_project_name, tmp_embedding_type, tmp_partition_name), tmp_df in records_df.groupby(['project_name',
                                                                                                  'embedding_type',
                                                                                                  'partition_name'
                                                                                                  ]):
        tmp_real_project_name = ProjectInfo.objects.get(name=tmp_project_name).real_name
        tmp_embedding_dim = embedding_name2dim_dict[tmp_embedding_type]
        # 向量数据库中建表
        # return_status = vector_db.build_collection(tmp_project_name, tmp_real_project_name, tmp_embedding_dim)
        # if return_status:
        #     logger.info(f'{tmp_project_name}_{tmp_embedding_dim}_ip创建成功或存在！')
        #     logger.info(f'{tmp_project_name}_{tmp_embedding_dim}_l2创建成功或存在！')
        # 若原来存在partition，删除
        return_status = vector_db.del_partition(tmp_project_name, tmp_partition_name, tmp_embedding_dim)
        if return_status:
            logger.info(f'删除{tmp_project_name}_{tmp_embedding_dim}_ip库向量分区{tmp_partition_name}')
            logger.info(f'删除{tmp_project_name}_{tmp_embedding_dim}_l2库向量分区{tmp_partition_name}')
        length = tmp_df.shape[0]

        model = choose_model(tmp_embedding_type)
        query_embedding_list = []
        for question in tmp_df["question"].tolist():
            query_embedding_list.append(model(question))

        user_id_list = [str(u) if u is not None else "" for u in tmp_df["user_id"].tolist()]

        # 写入到milvus中
        tmp_result_list = [
            tmp_df["code"].tolist(),
            tmp_df["question"].tolist(),
            query_embedding_list,
            user_id_list,
            tmp_df["session_id"].tolist(),
            [tmp_embedding_type] * length,
            tmp_df["source"].tolist(),
            [t.strftime("%Y-%m-%d %H:%M:%S") for t in tmp_df["create_time"].tolist()]
            # [datetime.now().strftime("%Y-%m-%d %H:%M:%S")]
        ]
        return_status, error_info = vector_db.insert_data(data=tmp_result_list, collection_name=tmp_project_name,
                                                          partition_name=tmp_partition_name, embedding_dim=tmp_embedding_dim)
        if not return_status:
            return JsonResponse({"status": 403, "msg": f"写入失败，发生错误{error_info}！"})

    return JsonResponse({"status": 200, "message": f"向量数据恢复成功！"})


@csrf_exempt
def delete_records(request):
    # 默认以下条件为需要同时满足
    condition = request.POST.get('condition', None)
    if condition is None:
        return JsonResponse({"status": 401, "message": "请输入参数condition!"})
    condition = json.loads(condition)
    project_name = request.POST.get("project_name", None)
    if project_name is None:
        return JsonResponse({"status": 401, "message": f"参数project_name不能为空!"})

    try:
        project = ProjectInfo.objects.get(name=project_name, status=1)
    except ProjectInfo.DoesNotExist:
        return JsonResponse({"status": 402, "message": f"项目 {project_name}不存在!"})
               
    expr_dict = {}
    for ck, cv in condition.items():
        if ck == "create_time":
            if len(cv.split()) == 1:
                cv = cv + " 0:0:0"
            expr_dict[ck+"__lte"] = datetime.strptime(cv, "%Y-%m-%d %H:%M:%S")
        else:
            expr_dict[ck+"__in"] = cv
    expr_dict["project_name"] = project
    expr_dict["status"] = 1
    delete_object_list = HistoryQA.objects.filter(**expr_dict)
    del_idx_dict = dict()
    del_num = 0
    for delete_object in delete_object_list:
        del_num += 1
        delete_code = delete_object.code
        embedding_type = delete_object.embedding_type.name
        embedding_dim = embedding_name2dim_dict[embedding_type]
        if embedding_dim not in del_idx_dict:
            del_idx_dict[embedding_dim] = [delete_code]
        else:
            del_idx_dict[embedding_dim].append(delete_code)
        delete_object.delete()
        
        
    if del_num == 0:
        return JsonResponse({"status": 200, "message": f"不存在符合条件的数据！"})
    # print(del_idx_dict)
    return_status = vector_db.delete_data(del_idx_dict, project_name)
    # question, user, session_id, embedding_type, source, create_time
    if return_status:
        return JsonResponse({"status": 200, "message": f"成功删除{del_num}条记录！"})
    else:
        return JsonResponse({"status": 200, "message": f"删除失败！"})
    